package cryptx

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"fmt"
	"golang.org/x/crypto/scrypt"
)

type DouYinPhone struct {
	CountryCode     string `json:"countryCode"`
	PhoneNumber     string `json:"phoneNumber"`
	PurePhoneNumber string `json:"purePhoneNumber"`
	Watermark       struct {
		Appid     string `json:"appid"`
		Timestamp int    `json:"timestamp"`
	} `json:"watermark"`
}

func PasswordEncrypt(salt, password string) string {
	dk, _ := scrypt.Key([]byte(password), []byte(salt), 32768, 8, 1, 32)
	return fmt.Sprintf("%x", string(dk))
}

//
//func Decrypt(encryptedData, sessionKey, iv string) string {
//
//	block, _ := aes.NewCipher(AESPrivateKey)
//	mode := cipher.NewCBCEncrypter(block, _iv)
//
//	mode.CryptBlocks(_encryptedData, _encryptedData)
//	return base64.StdEncoding.EncodeToString(_encryptedData)
//
//	//mode = cipher.NewCBCDecrypter(block, iv)
//	//mode.CryptBlocks(ciphertext, ciphertext)
//	//
//	//ciphertext = PKCS7UnPadding(ciphertext)
//}

/*
CBC 解密
encrypter 待解密的密文
key 秘钥
*/
func CBCDecrypter(encryptedData, sessionKey, iv string) string {

	key, _ := base64.StdEncoding.DecodeString(sessionKey)
	_iv, _ := base64.StdEncoding.DecodeString(iv)
	_encryptedData, _ := base64.StdEncoding.DecodeString(encryptedData)
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println(err)
	}
	blockMode := cipher.NewCBCDecrypter(block, _iv)
	result := make([]byte, len(_encryptedData))
	blockMode.CryptBlocks(result, _encryptedData)
	// 去除填充
	result = UnPKCS7Padding(result)
	return base64.StdEncoding.EncodeToString(result)
}

func Decrypt(encryptedData, sessionKey, iv string) string {
	src, _ := base64.StdEncoding.DecodeString(encryptedData)
	_key, _ := base64.StdEncoding.DecodeString(sessionKey)
	_iv, _ := base64.StdEncoding.DecodeString(iv)

	block, _ := aes.NewCipher(_key)
	mode := cipher.NewCBCDecrypter(block, _iv)
	dst := make([]byte, len(src))
	mode.CryptBlocks(dst, src)
	return string(dst)
}

/*
去除 PKCS7Padding 填充的数据
text 待去除填充数据的原文
*/
func UnPKCS7Padding(text []byte) []byte {
	// 取出填充的数据 以此来获得填充数据长度
	unPadding := int(text[len(text)-1])
	return text[:(len(text) - unPadding)]
}

func PKCS7Padding(ciphertext []byte) []byte {
	padding := aes.BlockSize - len(ciphertext)%aes.BlockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS7UnPadding(plantText []byte) []byte {
	length := len(plantText)
	unpadding := int(plantText[length-1])
	return plantText[:(length - unpadding)]
}
